import pyodbc
import json

from config import config

def execute_query(query_statement):
    # 创建MySQL连接
    cnxn = pyodbc.connect(f"""
        DRIVER={{MySQL ODBC 8.0 Unicode Driver}};
        SERVER={config.config_db['server']};
        PORT={config.config_db['port']};
        DATABASE={config.config_db['database']};
        USER={config.config_db['username']};
        PASSWORD={config.config_db['password']};
        charset=utf8mb4""")

    # 创建游标
    cursor = cnxn.cursor()

    # 执行查询
    cursor.execute(query_statement)

    rows = cursor.fetchall()
    columns = [column[0] for column in cursor.description]
    result = []
    for row in rows:
        result.append(dict(zip(columns, row)))

    # 关闭游标和连接
    cursor.close()
    cnxn.close()
    return json.dumps(result)

def execute_statement(sql_statement):
    # 创建MySQL连接
    cnxn = pyodbc.connect(f"""
        DRIVER={{MySQL ODBC 8.0 Unicode Driver}};
        SERVER={config.config_db['server']};
        PORT={config.config_db['port']};
        DATABASE={config.config_db['database']};
        USER={config.config_db['username']};
        PASSWORD={config.config_db['password']};
        charset=utf8mb4""")

    # 创建游标
    cursor = cnxn.cursor()

    # 执行查询
    cursor.execute(sql_statement)
    cursor.commit()

    rowcount = cursor.rowcount
    result = {"rowcount": cursor.rowcount}

    # 关闭游标和连接
    cursor.close()
    cnxn.close()
    return json.dumps(result)